package com.halotis.taskLauncher;

import static com.halotis.taskLauncher.Constants.*;

import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

public class CommandRules extends ArrayList<CommandRule> {

	private static final long serialVersionUID = 1L;
	
	// Singleton instance
	private static CommandRules rules = null;
	
	private CommandRules() throws Exception {
		Document xml = XmlHelper.getXmlDocument(RULE_XML_PATH);
		loadSettings(xml);
	}
	
	private void loadSettings(Document xml) {
		Element element = (Element)xml.getElementsByTagName("rules").item(0);
		NodeList settings = element.getElementsByTagName("rule");
		
		for (int i = 0; i < settings.getLength(); i++) {
			NamedNodeMap attributes = settings.item(i).getAttributes();
			
			String contains = attributes.getNamedItem("contains")==null? null : attributes.getNamedItem("contains").getNodeValue();
			String endsWith = attributes.getNamedItem("endsWith")==null? null : attributes.getNamedItem("endsWith").getNodeValue();
			String startsWith = attributes.getNamedItem("startsWith")==null? null : attributes.getNamedItem("startsWith").getNodeValue();
			String equals = attributes.getNamedItem("equals")==null? null : attributes.getNamedItem("equals").getNodeValue();
			String command = attributes.getNamedItem("command")==null? null : attributes.getNamedItem("command").getNodeValue();
			
			CommandRule rule = new CommandRule();
			rule.setCommand(command);
			rule.setContains(contains);
			rule.setEndsWith(endsWith);
			rule.setEquals(equals);
			rule.setStartsWith(startsWith);

			this.add(rule);
		}
	}

	public static CommandRules getInstance() throws Exception {
		if (rules == null) rules = new CommandRules(); 			
		return rules;
	}
	
}
